﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a seller comment.
    /// </summary>
    public class CreateSellerComment : CreateComment<SellerCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SALES");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) => ctx.Account(uow).EntityID == AccountID);
                yield return new SecurityPolicy()
                    .Rule((ctx, uow) => AccountID == 0);
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public SellerCommentFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            var seller = uow.Execute(new GetSeller
            {
                ThrowsException = true,
                EntityID = HolderID
            }).Result;
            if(!seller.Flags.HasFlag(SellerFlags.CommentAllowed))
                return Err.Of(this).NotAllowed();
            if(!uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Sales").Of<SellerCommentEntity>().Name("Allowed")
            }).ResultAs<Boolean>())
            {
                return Err.Of(this).NotAllowed();
            }

            var account = AccountID != 0 
                ? uow.Execute(new GetAccount
                {
                    ThrowsException = true,
                    EntityID = AccountID
                }).Result 
                : null;
            if(account == null)
            {
                if(!seller.Flags.HasFlag(SellerFlags.AnonCommentAllowed))
                    return Err.Of(this).NotAllowed().Reason("Anon");
                if(!uow.Execute(new GetConfigParamValueByKey
                {
                    Key = Par.In("Sales").Of<SellerCommentEntity>().Name("AnonAllowed")
                }).ResultAs<Boolean>())
                {
                    return Err.Of(this).NotAllowed().Reason("Anon");
                }
            }

            return base.Validate(uow);
        }

        protected override void Work(IUnitOfWork uow, out SellerCommentEntity result)
        {
            base.Work(uow, out result);

            uow.Execute(new UpdateSellerStats
            {
                EntityID = result.HolderID
            });

            try
            {
                uow.Execute(new EnqueueSellerCommentNotification
                {
                    CommentID = result.EntityID,
                    RecipientID = uow.Execute(new GetSeller
                    {
                        ThrowsException = true,
                        EntityID = result.HolderID
                    }).Result.Account.EntityID
                });
            }
            catch(Exception ex)
            {
                uow.Execute(new CreateLogRecordFromException
                {
                    Ex = ex
                });
            }
        }

        protected override void Construct(IUnitOfWork uow, SellerCommentEntity entity)
        {
            base.Construct(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the seller comment.
    /// </summary>
    public class UpdateSellerComment : UpdateComment<SellerCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SALES");
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public SellerCommentFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out SellerCommentEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdateSellerStats
            {
                EntityID = result.HolderID
            });
        }

        protected override void Revise(IUnitOfWork uow, SellerCommentEntity entity)
        {
            base.Revise(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the seller comment.
    /// </summary>
    public class DeleteSellerComment : DeleteComment<SellerCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SALES");
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow)
        {
            int holderID = uow.Execute(new GetSellerComment
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result.HolderID;

            base.Work(uow);

            uow.Execute(new UpdateSellerStats
            {
                EntityID = holderID
            });
        }

        #endregion
    }

    /// <summary>
    /// Gets the seller comment.
    /// </summary>
    public class GetSellerComment : GetComment<SellerCommentEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over seller comment collection.
    /// </summary>
    public class SearchSellerComments : SearchComments<SellerCommentEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchSellerComments()
        {
            SortDir = SortDirection.Ascending;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public SellerCommentFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<SellerCommentEntity> Build(IUnitOfWork uow, IQueryable<SellerCommentEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => x.FlagsValue, (int)FlagMask);
            query = query.OrderBy(x => x.CreatedOn, SortDir);
            return query;
        }

        #endregion
    }

    #endregion

    #region __Notification__

    /// <summary>
    /// Enqueues a seller comment notification message.
    /// </summary>
    /// <remarks>
    /// Message template code: NSLRCMT
    /// Allowed tokens: [T:Recipient.EntityID], [T:Recipient.Guid], [T:Recipient.Email], [T:Recipient.Username],
    /// [T:SellerComment.Seller.EntityID], [T:SellerComment.Seller.DisplayName], [T:SellerComment.Seller.RatingAverage],
    /// [T:SellerComment.Seller.CommentCount], [T:SellerComment.Seller.Account.EntityID], [T:SellerComment.Seller.Account.Email],
    /// [T:SellerComment.Seller.Account.Username], [T:SellerComment.Seller.Account.Guid], [T:SellerComment.Account.EntityID],
    /// [T:SellerComment.Account.Username], [T:SellerComment.Account.Email], [T:SellerComment.Account.Guid], [T:SellerComment.EntityID],
    /// [T:SellerComment.RatingCount], [T:SellerComment.Title], [T:SellerComment.Text], [T:SellerComment.CreatedOn]
    /// </remarks>
    public class EnqueueSellerCommentNotification : Operation<MessageEntity>
    {
        #region Properties

        /// <summary>
        /// Gets or sets the comment identifier.
        /// </summary>
        public int CommentID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the recipient account identifier.
        /// </summary>
        public int RecipientID
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out MessageEntity result)
        {
            var comment = uow.Execute(new GetSellerComment
            {
                ThrowsException = true,
                EntityID = CommentID
            }).Result;
            var recipient = uow.Execute(new GetAccount
            {
                ThrowsException = true,
                EntityID = RecipientID
            }).Result;
            var usrLocale = recipient.LocalizationProfile;
            int utcOffset = usrLocale.TimeZone.UtcOffset;
            string dtFmt = usrLocale.Country.DateTimeFormat;
            var seller = uow.Execute(new GetSeller
            {
                ThrowsException = true,
                EntityID = comment.HolderID
            }).Result;

            result = uow.Execute(new CreateTemplatedMessageByCode
            {
                TemplateCode = "NSLRREV",
                LanguageID = usrLocale.Language.EntityID,
                Replacements = new Dictionary<String, String>
                {
                    {"Recipient.EntityID", recipient.EntityID.ToString()},
                    {"Recipient.Email", recipient.Email},
                    {"Recipient.Username", recipient.Username},
                    {"Recipient.Guid", recipient.Guid.ToString()},
                    {"SellerComment.Seller.EntityID", seller.EntityID.ToString()},
                    {"SellerComment.Seller.DisplayName", seller.DisplayName},
                    {"SellerComment.Seller.RatingAverage", seller.RatingAverage.ToString()},
                    {"SellerComment.Seller.CommentCount", seller.CommentCount.ToString()},
                    {"SellerComment.Seller.RatingCount", seller.RatingCount.ToString()},
                    {"SellerComment.Seller.Account.EntityID", seller.Account.EntityID.ToString()},
                    {"SellerComment.Seller.Account.Email", seller.Account.Email},
                    {"SellerComment.Seller.Account.Username", seller.Account.Username},
                    {"SellerComment.Seller.Account.Guid", seller.Account.Guid.ToString()},
                    {"SellerComment.Account.EntityID", comment.Account != null 
                        ? comment.Account.EntityID.ToString() 
                        : String.Empty},
                    {"SellerComment.Account.Username", comment.Account != null 
                        ? comment.Account.Username 
                        : String.Empty},
                    {"SellerComment.Account.Email", comment.Account != null 
                        ? comment.Account.Email 
                        : String.Empty},
                    {"SellerComment.Account.Guid", comment.Account != null 
                        ? comment.Account.Guid.ToString() 
                        : String.Empty},
                    {"SellerComment.EntityID", comment.EntityID.ToString()},
                    {"SellerComment.Title", comment.Title},
                    {"SellerComment.Text", comment.Text},
                    {"SellerComment.CreatedOn", comment.CreatedOn.ToLocal(utcOffset).ToStringByFmt(dtFmt)}
                },
                To = recipient.Email,
                Flags = MessageFlags.Active
            }).Result;
        }

        #endregion
    }

    #endregion
}
